const scanImports = require('./scan')
const { build } = require('esbuild')
const fs = require('fs-extra')
const path = require('path')
const { normalizePath } = require('../utils')
/**
 * 分析项目依赖的第三方模块
 * @param {*} config
 */
async function createOptimizeDepsRun(config) {
  // deps={ 'vue': 'c:/node_modules/vue/dist/vue.global.js' }
  const deps = await scanImports(config)
  const { cacheDir } = config
  const depsCacheDir = path.resolve(cacheDir, 'deps')
  const metadataPath = path.resolve(depsCacheDir, '_metadata.json')
  const metadata = {
    optimized: {},
  }
  console.log(deps)
  for (const name in deps) {
    const entry = deps[name]
    // 内存里存的绝对路径，写入硬盘是相对路径
    const file = path.resolve(depsCacheDir, `${name}.js`)
    metadata.optimized[name] = {
      src: entry,
      file,
    }
    // 生成第三方模块的代码 esbuild 进行预编译
    await build({
      absWorkingDir: process.cwd(),
      entryPoints: [deps[name]],
      outfile: file,
      bundle: true,
      format: 'esm',
      write: true,
    })
  }
  await fs.ensureDir(depsCacheDir)
  // 写入缓存
  await fs.writeFile(
    metadataPath,
    JSON.stringify(metadata, (key, value) => {
      if (key === 'file' || key === 'src') {
        return normalizePath(path.relative(depsCacheDir, value))
      }
      return value
    })
  )
  return {
    metadata,
  }
  console.log(deps)
}

exports.createOptimizeDepsRun = createOptimizeDepsRun
